import Global from "@/Global";
import axios from "axios";
import { getPlatform } from "./phone";
import md5 from '../util/md5'
import { clearAll, GetAPPUserType, getPersonID, getToken } from './session'
import { Toast } from "vant";
import axiosRetry from 'axios-retry'

const appID = '123sfexzcx'; const appKey = 'pow309psdjfw';
const backdoorFlag = 0;
//vue
let context = null
function initContext(vue){
	context = vue;
}
//自定义
let myAxios = axios.create({
	baseURL: Global.api_url,
	timeout: 10 * 1000,
})
//失败请求配置 重试默认条件：返回状态码：5xx 重试间隔1秒钟，总共请求次数3次
axiosRetry(myAxios, { retries: 3, retryDelay: (retryCount) => { return retryCount * 1000 } });
//响应拦截
myAxios.interceptors.response.use(res => {
	// console.log(res) //object:{status:xxx,data:{status:xxx,msg:'xxx',response:object,success}}
	if (res.data.status) {
		if (res.data.status == 200 || res.data.status == 204) { return Promise.resolve(res) }
		else {
			switch (res.data.status) {
				case 400:
					//未授权
					Toast('无效的请求');
					break;
				case 401:
					//未授权
					Toast('您无权限这样做');
					break;
				case 403:
					//未认证
					Toast('您无权限这样做');
					break;
				case 404:
					//无资源
					Toast('访问的资源不存在');
					break;
				case 415:
					//请求方式不对
					Toast('无效的请求方式');
					break;
				case 500:
					//服务器错误
					Toast('服务器错误');
					break;
				default:
					break;
			}
			return Promise.resolve(res);
		}
	}
	return Promise.resolve(res)
}, err => {
	//得到返回值
	//console.log(err) //-- object:{response:{status:xxx,data:{status:xxx,msg:'xxx',response:object,success}}}
	if (err.response && err.response.status) {
		let data = err.response.data;
		Toast(data.msg);
		//token失效 
		if (data.status == 401) {
			//重新登录
			let userType = GetAPPUserType();
			//已登录状态
			if (userType && userType == 'P') { clearAll(); context.$router.replace({ name: 'person-login' }) }
			else if (userType && userType == 'C') {clearAll(); context.$router.replace({ name: 'company-login' }) }
		}

	}
	//未得到返回值
	else {
		if (err.message.indexOf('timeout') != -1) { Toast.fail('请求超时，请稍后再试') }
		else { Toast.fail(err.message); }
	}
	return Promise.reject(err);
})


let get = function get(_url, _params) {
	let timestamp = new Date().getTime();
	return myAxios.get(_url, {
		params: _params,
		headers: { Authorization: 'Bearer ' + getToken(), platform: getPlatform(), appID: appID, timestamp: timestamp, sign: getSignStr(timestamp), "content-type": "application/json", backdoorFlag: backdoorFlag },
	}).then(res => {
		return res.data;
	})
}
let post = function post(_url, _data) {
	let timestamp = new Date().getTime();
	return myAxios.post(_url, _data, {
		headers: { Authorization: 'Bearer ' + getToken(), platform: getPlatform(), appID: appID, timestamp: timestamp, sign: getSignStr(timestamp), "content-type": "application/json", backdoorFlag: backdoorFlag },
	}).then((res) => {
		return res.data;
	})
}

//签名
function getSignStr(timestamp) {
	return md5.md5(timestamp.toString() + appID + appKey);
}

let pActions = { Login: '/PersonAccount/Login', GetHisSearchKeywords: '/PersonStation/GetHisSearchKeywords' }
export default {
	axios, get, post, pActions,initContext
}